import React, { useImperativeHandle, useState, forwardRef } from "react";
import { CommonComponenetProps } from "../../interface";
import { Modal as AntdModal } from 'antd';

export interface ModalRef {
    open: () => void;
    close: () => void;
}

// 使用 React.ForwardRefRenderFunction<ModalRef, CommonComponenetProps>
const Modal: React.ForwardRefRenderFunction<ModalRef, CommonComponenetProps> = ({ children, title, onOk, onCancel, styles }, ref) => {
    const [open, setOpen] = useState(false);  // 初始状态为 false，模态框是关闭的
    console.log("ref", ref)

    // 使用 useImperativeHandle 让父组件可以调用 open 和 close
    useImperativeHandle(ref, () => ({
        open() {
            setOpen(true);
        },
        close() {
            setOpen(false);
        }
    }));

    return (
        <AntdModal
            title={title}
            style={styles}
            open={open}
            onOk={() => {
                if (onOk) onOk();  // 先调用传递的 onOk 函数
                setOpen(false);    // 关闭模态框
            }}
            onCancel={() => {
                if (onCancel) onCancel();  // 先调用传递的 onCancel 函数
                setOpen(false);            // 关闭模态框
            }}
            destroyOnClose
        >
            {children}
        </AntdModal>
    );
};

export default forwardRef(Modal);
